const app = getApp()

Page({
  data: {
    userInfo: null,
    version: '',
    versionTapCount: 0,
    showStaffLogin: false
  },

  onLoad() {
    // 获取小程序版本号
    const accountInfo = wx.getAccountInfoSync()
    if (accountInfo && accountInfo.miniProgram) {
      this.setData({
        version: accountInfo.miniProgram.version || '1.0.0'
      })
    }
    this.checkLogin()
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    this.checkLogin()
  },

  checkLogin() {
    const token = wx.getStorageSync('access_token')
    if (!token) {
      this.setData({ userInfo: null })
      return
    }

    // 获取用户信息
    wx.request({
      url: `${app.globalData.baseUrl}/users/profiles/me/`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        console.log('获取用户信息成功:', res.data)
        if (res.statusCode === 200) {
          this.setData({ 
            userInfo: {
              ...res.data,
              nickname: res.data.nickname || res.data.username,
              avatar_url: res.data.avatar_url || '/assets/images/default-avatar.png'
            }
          })
        } else if (res.statusCode === 401) {
          // token可能过期，尝试刷新
          const refreshToken = wx.getStorageSync('refresh_token')
          if (refreshToken) {
            this.refreshToken(refreshToken)
          } else {
            this.clearTokenAndRedirect()
          }
        }
      },
      fail: (err) => {
        console.error('获取用户信息失败:', err)
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    })
  },

  refreshToken(refreshToken) {
    wx.request({
      url: `${app.globalData.baseUrl}/token/refresh/`,
      method: 'POST',
      data: {
        refresh: refreshToken
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.setStorageSync('access_token', res.data.access)
          this.checkLogin()
        } else {
          this.setData({ userInfo: null })
          wx.removeStorageSync('access_token')
          wx.removeStorageSync('refresh_token')
        }
      },
      fail: () => {
        this.setData({ userInfo: null })
        wx.removeStorageSync('access_token')
        wx.removeStorageSync('refresh_token')
      }
    })
  },

  clearTokenAndRedirect() {
    wx.removeStorageSync('access_token')
    wx.removeStorageSync('refresh_token')
    this.setData({ userInfo: null })
    wx.redirectTo({
      url: '/pages/login/login?redirect=' + encodeURIComponent('/pages/profile/profile')
    })
  },

  goToOrders() {
    const token = wx.getStorageSync('access_token')
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login?redirect=' + encodeURIComponent('/pages/order-list/order-list')
      })
      return
    }

    // 使用switchTab而不是navigateTo，因为订单列表是tabBar页面
    wx.switchTab({
      url: '/pages/order-list/order-list',
      fail: (err) => {
        console.error('跳转失败:', err)
        // 如果switchTab失败，尝试navigateTo
        wx.navigateTo({
          url: '/pages/order-list/order-list'
        })
      }
    })
  },

  goToAddress() {
    if (!this.checkLoginStatus()) return
    wx.navigateTo({
      url: '/pages/address/address'
    })
  },

  contactService() {
    wx.makePhoneCall({
      phoneNumber: '400-123-4567'
    })
  },

  showAbout() {
    wx.navigateTo({
      url: '/pages/about/about'
    })
  },

  onVersionTap() {
    console.log('版本号被点击')
    let count = this.data.versionTapCount + 1
    console.log('当前点击次数:', count)
    
    this.setData({ versionTapCount: count })
    
    if (count >= 5) {
      console.log('显示工作人员登录')
      wx.navigateTo({
        url: '/pages/staff-login/index'
      })
      this.setData({ versionTapCount: 0 })
    }
  },

  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除登录状态
          wx.removeStorageSync('access_token')
          wx.removeStorageSync('refresh_token')
          this.setData({ userInfo: null })
          // 返回首页
          wx.switchTab({
            url: '/pages/index/index'
          })
        }
      }
    })
  },

  checkLoginStatus() {
    if (!this.data.userInfo) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return false
    }
    return true
  }
})